define(function(require, exports, module) {

  "require:nomunge,exports:nomunge,module:nomunge";


/************************** 切换tab的回调函数 *****************************/

  var tabFn = [];

  /**
   * 第一次加载
   */
  /**
   * 消息滚动到底部加载的函数
   * @return {[type]} [description]
   */
  tabFn[1] = function(type)
  {
    $('.loadAllOverBox').hide();
    // scroll ajax
    var lastUptime = $('.messageListBox .messageBox:last').attr('data-update_time_ms') || '';
    var url = bg.mpApi.getUrl('user/extension/extension_get_message', true);

    var data = {
      keyword: $.trim($('#searchText').val()),
      startT : $.trim($('#searchStartTime').val()),
      endT   : $.trim($('#searchEndTime').val()),
      msgType: $('#searchMsgType').val(),
      last_id: lastUptime,
      get_old: 1
    };

    if(!$('.messageListBox .messageBox:last').length) {
      data.get_old = 0;
    }

    common.loading(true);
    $.getJSON(url, data, function(json){
      common.loading(false);
      if ( json.info != 'ok' ) {
        common.showMsg(json.info);
        return;
      }
      if ( !json.message_list || !json.message_list.length ) {
        $('.loadAllOverBox').slideDown();
        return;
      }
      bg.mpApi.getToken(function(token){
        if (!token) {
          bg.mpApi.setSwitchPage('message');
          common.showMsg('获取token失败，请保持公众平台页面处于打开状态 '+'<a href="https://mp.weixin.qq.com" target="_blank">点此打开</a>');
          return;
        }
        common.hideMsg();
        // 渲染
        var html = '';
        $.each(json.message_list, function(k, v){
          html += renderMessage(v, token);
        });
        $('.messageListBox').append(html);
        $('.showAdminUrlBtn .num').text(json.total+'条');
        $('#navbar li[data-id="1"]').find('.navNum').text('('+json.total+')');
        bg.mpApi.setNoticeNum(json.total);
        $('.wallMessageTotal').show();
        $('.searchBox').show();
        $('.messageListBox').show();
      });
    }).error(function(jqXHR, errTxt){
      common.loading(false);
      common.showMsg("加载上墙消息错误，网络错误("+errTxt+")");
    });
  };


  /**
   * 加星消息的滚动的回调函数
   */
  tabFn[2] = function(type)
  {
    common.loading(true);
    $('.tagLoadAllOverBox').hide();
    // scroll ajax
    var lastId = $('.tagMessageListBox .tagMessageBox:last').attr('data-tag_relation_id');
    var url = bg.mpApi.getUrl('user/extension/extension_get_tag_message', true);

    var data = {
      last_id: lastId,
      tag_id: 1
    };

    $.getJSON(url, data, function(json){
      common.loading(false);
      if ( json.info != 'ok' ) {
        common.showMsg(json.info);
        return;
      }
      if ( !json.message_list || !json.message_list.length ) {
        $('.tagLoadAllOverBox').slideDown();
        return;
      }
      bg.mpApi.getToken(function(token){
        if (!token) {
          bg.mpApi.setSwitchPage('message');
          common.showMsg('获取token失败，请保持公众平台页面处于打开状态 '+'<a href="https://mp.weixin.qq.com" target="_blank">点此打开</a>');
          return;
        }
        common.hideMsg();
        // 渲染
        var html = '';
        $.each(json.message_list, function(k, v){
          if($('.tagMessageBox[data-id="'+v.id+'"]').length) {
            // continue;
            return true;
          }
          html += renderTagMessage(v, token);
        });
        $('.tagMessageListBox').append(html);
        $('#navbar li[data-id="2"]').find('.navNum').text('('+json.total+')');
      });
    });
  };

  /**
   * 中奖用户列表
   */
  tabFn[3] = function (type)
  {
    var localData = bg.mpApi.getLocalLotteryData();
    if(localData && localData.length > 0) {
      loadWinnerLocal(localData, 1)
      return;
    };

    common.loading(true);
    // 请求中奖名单数据，第一页
    loadWinnerAjax(1);
  };

  /**
   * 渲染二维码
   */
  tabFn[4] = function()
  {
    // 渲染公司信息
    var companyInfo = bg.mpApi.getCompanyInfo();
    if(!companyInfo) return false;
    if(!companyInfo.weixin_qr) {
      common.showMsg('当前的大屏幕“<em>'+companyInfo.title+'</em>”还未配置成功，您可以点击<a class="btn btn-mini btn-danger" href="###" id="enterSettingPageBtn">此处</a>去配置');
      $('.qrBox').hide();
      return;
    }
    $('.qrBox .qrImg').attr('src', companyInfo.weixin_qr);
    $('.qrBox .qrName').html(companyInfo.weixin_name);
    $('.qrBox').show();
  };
  
  // 大屏幕遥控器
  tabFn[5] = function()
  {
    // 获取二维码
    var companyInfo = bg.mpApi.getCompanyInfo();
    if(!companyInfo) return false;
    var url = bg.mpApi.getUrl('user/extension/get_ykq_qr', true);
    $.getJSON(url, function(json){
      if(json.info == 'ok') {
        $('.ykqQr').attr('src', json.url);
      } else {
        alert(json.info);
      }
    }).error(function(){
      //alert("网络错误，获取二维码失败");
    });
    
    if(this.initedEvent) return;
    
    $('#resetYkqQrBtn').click(function(){
      var url = bg.mpApi.getUrl('user/extension/reset_ykq_qr', true);
      // 获取二维码
      var companyInfo = bg.mpApi.getCompanyInfo();
      if(!companyInfo) return false;
      $.post(url, function(json){
        if(json.info == 'ok') {
          $('.ykqQr').attr('src', json.url);
        } else {
          alert(json.info)
        }
      }, 'json').error(function(){
        
      });
    });
  };

  // 加载中奖名单，先从本地，如果本地没有就走请求，点击分页的时候，用到了
  loadWinnerData = function(page)
  {
    // 首先是从本地加载
    var localData = bg.mpApi.getLocalLotteryData();
    if(localData && localData.length > 0) {
      loadWinnerLocal(localData, page)
      return;
    };
    // 请求中奖名单数据
    loadWinnerAjax(page);
  }
  
  // 从本地加载
  loadWinnerLocal = function(localData, page)
  {
    console.log('from local');
    // 本地存储的名单数量
    var totalLocalNum = localData.length;
    var totalPage = getWinnerTotalPage(localData.length);
    
    // 分页
    bg.mpApi.getToken(function(token){
      if (!token) {
        bg.mpApi.setSwitchPage('message');
        common.showMsg('获取token失败，请保持公众平台页面处于打开状态 '+'<a href="https://mp.weixin.qq.com" target="_blank">点此打开</a>');
        return;
      }
      common.hideMsg();

      var newlocalData = getWinnerData(localData, page);
      if(!newlocalData.length) {
        common.showMsg("暂无中奖用户");
        return;
      }

      // 渲染
      var html = '';
      for (i in newlocalData) {
////        if($('.lotteryUserBox[data-id="'+v.id+'"]').length) {
////          // continue;
////          return true;
////        }
        html += renderLotteryUser(newlocalData[i], token);

      }
      $('.lotteryUserListBox').html("").append(html);
      $('#navbar li[data-id="3"]').find('.navNum').text('('+totalLocalNum+')');
      
      // 处理分页
      if (totalPage > 1) {
        var pageHtml = renderPageHtml(totalLocalNum, page);
        $('.winnerPage ul').html(pageHtml);
        $('.winnerPage').show().removeClass('hidden');
      } else {
        $('.winnerPage ul').html('').hide();
      }
    });
  }
  
  /**
   * 计算总页数
   */
  getWinnerTotalPage = function(totalNum)
  {
    return Math.ceil(totalNum/4);
  }
  /**
   * 本地没有的情况下，走ajax请求
   */
  loadWinnerAjax = function(page)
  {
    console.log('from ajax');
    var url = bg.mpApi.getUrl('user/extension/extension_get_lottery', true);
    $.getJSON(url, { 'page_no':page }, function(json){
      common.loading(false);
      if ( json.info != 'ok' ) {
        common.showMsg(json.info);
        return;
      }
      if ( !json.lottery_list || !json.lottery_list.length ) {
        common.showMsg("暂无中奖用户");
        return;
      }
      bg.mpApi.getToken(function(token){
        if (!token) {
          bg.mpApi.setSwitchPage('message');
          common.showMsg('获取token失败，请保持公众平台页面处于打开状态 '+'<a href="https://mp.weixin.qq.com" target="_blank">点此打开</a>');
          return;
        }
        common.hideMsg();
        // 渲染
        var html = '';
        $.each(json.lottery_list, function(k, v){
//          if($('.lotteryUserBox[data-id="'+v.id+'"]').length) {
//            // continue;
//            return true;
//          }
          html += renderLotteryUser(v, token);
        });
        $('.lotteryUserListBox').html("").append(html);
        $('#navbar li[data-id="3"]').find('.navNum').text('('+json.total+')');
        
        // 处理分页
        if (json.total_page > 1) {
          $('.winnerPage ul').html(json.page_html);
          $('.winnerPage').show().removeClass('hidden');
        } else {
          $('.winnerPage ul').html('').hide();
        }
      });
    });
  }
  
  /**
   * 从本地获取中，用到了，用户返回指定分页的数据
   */
  getWinnerData = function(winnerList, currPage)
  {
    var winnerLength = winnerList.length;
    var totalPage    = Math.ceil(winnerLength/4);
    var startKey     = (currPage-1)*4;
    
    var tmpArr = new Array();
    if (currPage > totalPage) {
      return tmpArr;
    }
    if ((startKey+4) > winnerLength) {
      lastKey = winnerLength - 1;
    } else {
      lastKey = startKey+4 - 1;
    }
    for (var i=startKey; i<=lastKey; i++) {
    tmpArr[i] = winnerList[i];
    }
    return tmpArr;
  }
  
  
  // 获取分页结构，每页4个，一共显示7页。
  renderPageHtml = function(totalNum, currPage)
  {
    var totalPage = Math.ceil(totalNum/4);
    var showNum   = 7;
    var beforeNum = 3;
    var afterNum  = 3;
    if (currPage == undefined) {
      var currPage = 1;
    }
    // 只有1页不用显示分页
    if (totalPage <= 1) {
      return '';
    }
    
    // 只有7页，全部显示
    if (totalPage <= showNum) {
      var startPage = 1;
      var endPage   = totalPage;
    } else {
      if (currPage > beforeNum && currPage <= (totalPage-afterNum)) {
        // 前面3个，后面3个
        var startPage = currPage-beforeNum;
        var endPage   = parseInt(currPage)+parseInt(afterNum);
      } else if (currPage <= beforeNum) {
        // 取前面所有，不足的用后面补。
        var startPage = 1;
        var endPage   = showNum;
      } else if (currPage > (totalPage-afterNum)) {
        // 取后面所有，不足的用前面补。
        var startPage = totalPage - 6;
        var endPage   = totalPage;
      }
    }
    var prevPage = getPrevPageNum(currPage, startPage);
    var nextPage = getNextPageNum(currPage, endPage);
  
    var pageHtml = '<ul><li ';
    if (currPage == 1) {
      pageHtml+=' class="disabled" ';
    }
    pageHtml+= ' id="page'+prevPage+'"><a href="javascript:void(0);">«</a></li>';
    
    for (var i=startPage; i<=endPage; i++) {
      pageHtml+= '<li ';
      if (currPage == i) {
        pageHtml+=' class="disabled" ';
      }
      pageHtml+= ' id="page'+i+'"><a href="javascript:void(0);">第'+i+'页</a></li>';
    }
    pageHtml += '<li ';
    if (currPage == totalPage) {
      pageHtml+=' class="disabled" ';
    }
    pageHtml += ' id="page'+nextPage+'"><a href="javascript:void(0);">»</a></li></ul>';
    return pageHtml;
  }
  
  function getPrevPageNum(currPage, startPage)
  {
    if (currPage == startPage) {
    return startPage;
    }
    return currPage -1;
  }
  
  function getNextPageNum(currPage, endPage)
  {
    if (currPage == endPage) {
        return endPage;
    }
    return parseInt(currPage)+1;
  }
  

  /************************** tabFn end ********************************/





  // 依赖的模块
  var common = require('/module/common/common.js');
  // jquery
  var $      = require('jquery');
  // 背景
  var bg     = chrome.extension.getBackgroundPage();
  // 上一次上墙消息更新的id
  var lastId = '';

  // 自动填写用户名
  rememberAccount(true);

  // 普通全局事件
  generalEvent();

  // 检查登录
  var url = bg.mpApi.getUrl('user/extension/check_login');
  $.getJSON(url, function(data){
    // 关闭桌面通知
    bg.mpNotification.close('user_login');
    bg.mpNotification.close('mp_message_ready');

    common.loading(false);
    common.hideMsg();
    if ( data.is_login == false ) {
      notLoginHandler();
    } else {
      // 已登录（是否已配置ok等等...）
      bg.mpApi.setFirstCheckLoginInfo(data);
      loginedHandler(data);
      showVersionTip();
    }
  }).error(function(jqXHR, errText){
    var data = bg.mpApi.getFirstCheckLoginInfo();
    if(!data) {
      common.showMsg("网络异常，登录失败："+errText);
      return;
    }
    // 关闭桌面通知
    bg.mpNotification.close('user_login');
    bg.mpNotification.close('mp_message_ready');

    common.loading(false);
    common.hideMsg();
    loginedHandler(data);
    showVersionTip();
  });

  /**
   * 未登录的处理
   */
  function notLoginHandler()
  {
    common.loginBox(true);

    // qq登录
    $("#qqloginSubmitBtn").click(function (){
      $('body').css({'padding':'0px', 'width':'730px', 'height':'440px'});
      $("#authbox > iframe").attr('src', bg.mpApi.getUrl('openapi/qqconnect/login', false));
        $("#authbox, #authbox_bg").show();
        $('#authbox').siblings().not('#authbox_bg').css('visibility', 'hidden');
        // 轮询登录
        loginPoll();
    });

    // 初始化事件
    $('.registerBtn').click(function(){
      window.open(bg.mpApi.getUrl('user/register'));
    });
    $('#userName, #password').keyup(function(){
      common.hideMsg();
      rememberAccount();
    });
    // 提交表单
    $('#loginForm').submit(function(e){
      e.preventDefault();
      var userName = $.trim($('#userName').val());
      var password = $.trim($('#password').val());

      rememberAccount();
      $.post(bg.mpApi.getUrl('user/login?is_extension=1'), { 'username':userName, 'password':password }, function(json){
        if ( json.info != 'ok' ) {
          common.showMsg(json.info);
          return;
        }
        common.loginBox(false);
        // 已经登录（是否已配置ok等等...）
        loginedHandler(json);
        showVersionTip();
      }, 'json');
    });
  }

  /**
   * 记住账号名
   */
  function rememberAccount(isGet)
  {
    if (isGet) {
      var storeAccount = localStorage.getItem('account_name');
      if (storeAccount) {
        $('#userName').val(storeAccount);
      }
    } else {
      var isRemember = $('input[name="remember_account"]:checked').length;
      if (isRemember) {
        var userName = $.trim($('#userName').val());
        if (userName) {
          localStorage.setItem('account_name', userName);
        }
      } else {
        localStorage.setItem('account_name', '');
      }
    }
  }

  /**
   * 登录后的处理
   */
  function loginedHandler(json)
  {
    // 查看是否配置好
    if ( !json.is_login ) {
      common.showMsg('登录失败！请联系管理员');
      return;
    }

    bg.mpApi.setUserInfo(json.user_info);
    bg.mpApi.setCompanyInfoList(json.company_info_list);

    var currCompanyInfo = bg.mpApi.getCompanyInfo();

    if(!currCompanyInfo) {
      var url = bg.mpApi.getUrl('user/apply');
      common.showMsg('您还没有可用的大屏幕，点击<a class="btn btn-mini btn-primary" href="'+url+'" target="_blank">此处</a>去创建');
      return;
    }

    // 渲染当前的大屏幕
    var options = '';
    $.each(json.company_info_list, function(){
      options += '<option value="'+this.id+'">'+this.title+'</option>';
    });
    $('#companyListSel').html(options);
    $('#companyListSel').val(currCompanyInfo.id);

    // 显示绑定信息
    $('.userInfo').show().find('em').text(currCompanyInfo.weixin_name);

    var autoWallStatus = bg.mpApi.getAutoWallStatus();
    if (autoWallStatus == 1) {
      $('.autoWallBtn').removeClass("btn-success").addClass('btn-danger').text("关闭自动上墙").show();
    } else {
      $('.autoWallBtn').removeClass("btn-danger").addClass('btn-success').text("开启自动上墙").show();
    }

    // 恢复自动上墙的数据
    bg.mpApi.taskUnserialize();

    // 显示设置按钮
    $('.settingBtn').show();

    // 是否自动上墙
    if (currCompanyInfo.is_auto_wall == 1) {
      $('#htmlCount').show();
      $('#htmlTime').show();
      $('#wallTime').show();
    } else {
      $('.autoWallBtn').hide();
      // 改为批量上墙
      $('.autoWallLabel').text("批量上墙选项");
    }

    // 显示popup的消息数量
    bg.mpApi.getWallMessageTotal(function(err, data){
      if ( data && data.info == 'ok' && data.total ) {
        bg.mpApi.setNoticeNum(data.total);
      } else {
        bg.mpApi.setNoticeNum('');
      }
    });

    // 设置完全匹配的关键字
    bg.mpApi.setRuleWords(currCompanyInfo.complete_forbid_words, 'complete');
    // 设置过滤关键词
    bg.mpApi.setRuleWords(currCompanyInfo.forbid_words, 'match');
    // 设置允许上墙的关键字
    bg.mpApi.setRuleWords(currCompanyInfo.auto_wall_matched_words, 'auto_wall');
    // 设置系统关键词
    bg._cache['forbid_words_default_arr'] = json.forbid_words_default.split('@');

    // 设置自动上墙开始时间
    bg._cache['auto_wall_start_time'] = currCompanyInfo.auto_wall_start_time;
    // 设置是否屏蔽重复上墙
    bg._cache['is_allow_user_repeat_message'] = parseInt(currCompanyInfo.is_allow_user_repeat_message);


    // 微信名字是否获取到
    if ( bg.mpApi.isNeedSetting() ) {
      var tmpTip = json.company_info_list.length > 1 ? "<br/><br/>点击右上角选择框切换您当前的大屏幕" : "";
      common.showMsg('当前的大屏幕“<em>'+currCompanyInfo.title+'</em>”还未配置成功<br/>您可以<a class="btn btn-mini btn-danger" href="###" id="enterSettingPageBtn">点击此处</a>去配置'+tmpTip);
      $('.wallMessageTotal').show();
      return;
    }

    // 是否显示中奖用户发送框
    if(currCompanyInfo.open_send_lottery_message == 1) {
      $('#lotterySendMessageBox').show();
    }

    // 切换tab
    $('#navbar li:eq(0)').trigger('click');

    $('#content').show();
    $('.wallMessageTotal').show();

  }

  /**
   * 全局的事件绑定
   */
  function generalEvent()
  {
    // 关闭
    $('.close').click(function(){
      $(this).closest('.closeBox').fadeOut();
    });

    // 重置大屏幕二维码
    $('#reconfigBtn').click(function(){
      var clickObj = $(this);
      $(this).closest('p').hide().next('p').show();
    });
    // 取消重置
    $('.cancelReconfig').click(function(){
      var clickObj = $(this);
      $(this).closest('p').hide().prev('p').show();
    });
    
    // 继续重置
    $('.continueReconfig').click(function(){
      var thisBtn = $(this);
      if(thisBtn.attr('data-disabled') == 'yes') {
        common.showMsg("请稍等，正在重新配置中...");
        return false;
      }
      $('.cancelReconfig').hide();
      var url = bg.mpApi.getUrl("user/extension/reconfig", true);
      thisBtn.attr('data-disabled', 'yes').addClass('disabled').text("正在配置...");
      $.post(url, function(json){
        if(json.info == 'ok') {
          thisBtn.attr('data-disabled', 'no').text("正在获取二维码...");
          var tmpCompany = bg.mpApi.getCompanyInfo();
          tmpCompany.weixin_qr = '';
          tmpCompany.weixin_qr_big = '';
          tmpCompany.weixin_qr_middle = '';
          bg.mpApi.setCompanyInfo(tmpCompany);

          bg._cache['is_setting_complete'] = false;
          setInterval(function(){
            if(bg._cache['is_setting_complete'] === true) {
              window.location.reload();
            }
          }, 50);

          enterMpSettingPage();
          // 去配置
        } else {
          common.showMsg(json.info);
          thisBtn.attr('data-disabled', 'no').removeClass('disabled').text('继续');
          $('.cancelReconfig').show();
          thisBtn.closest('p').hide().prev('p').show();
        }
      }, 'json').error(function(jqXHR, errText){
        thisBtn.attr('data-disabled', 'no');
        common.showMsg("网络错误："+errText+"，请重试");
      });
    });

    // 去配置
    $('#enterSettingPageBtn').live("click", function(){
      enterMpSettingPage();
    });

    // 切换tab
    $('#navbar li').click(function(){
      var id = parseInt($(this).data('id'));
      $(this).addClass('active').siblings('li').removeClass('active');
      $('.bar-container').hide();
      $('.bar-container[data-id="'+id+'"]').show();
      common.hideMsg();
      // 触发事件
      tabFn[id]();
    });
    
    // 点击分页，加载相应的名单
    $('.winnerPage').delegate('li', 'click', function(){
      if ($(this).hasClass('disabled')) {
        return;
      }
      var loadPage = $(this).attr('id').substring('4');
      if (!loadPage) {
        return;
      }
      loadWinnerData(loadPage);
//      loadWinnerAjax(loadPage);
    });

    // 全部去掉打包标签
    $('.untagAllBtn').click(function(){
      var thisBtn = $(this);
      if(thisBtn.attr('data-disabled') == 'yes') {
        //alert('请稍候~');
        return;
      }
      var url = bg.mpApi.getUrl('user/extension/untag_all', true);

      thisBtn.attr('data-disabled', 'yes');
      $.post(url, {'tag_id':1}, function(json){
        thisBtn.attr('data-disabled', 'no');
        if(json.info == 'ok') {
          common.showMsg("全部取消成功");
          $('.tagMessageBox').remove();
          $('#navbar li[data-id="2"]').find('.navNum').text("(0)");
        } else {
          alert(json.info);
        }
      }, 'json').error(function(){
        thisBtn.attr('data-disabled', 'no');
      });
    });

    // 去掉打包标签
    $('.untagBtn').live('click', function(){
      var thisBtn = $(this);
      if(thisBtn.attr('data-disabled') == 'yes') {
        //alert('请稍候~');
        return;
      }
      var relationId = $(this).closest('.tagMessageBox').data('tag_relation_id');
      var url = bg.mpApi.getUrl('user/extension/untag', true);

      thisBtn.attr('data-disabled', 'yes');
      $.post(url, {'relation_id':relationId}, function(json){
        if(json.info == 'ok') {
          thisBtn.closest('.tagMessageBox').fadeOut(function(){
            $(this).remove();
          });
          $('#navbar li[data-id="2"]').find('.navNum').text("("+json.total+")");
        } else {
          alert(json.info);
        }
      }, 'json').error(function(){
        thisBtn.attr('data-disabled', 'no');
      });
    });

    // 切换我的大屏幕
    $('#companyListSel').change(function(){
      var nowId = $(this).val(), nowInfo;
      var companyList = bg.mpApi.getCompanyInfoList();
      if(!companyList) return false;
      $.each(companyList, function(){
        if(this.id == nowId) {
          nowInfo = this;
          return false;
        }
      });
      if(!nowInfo) return false;
      bg.mpApi.setCompanyInfo(nowInfo);
      // ...关闭其他的插件
      bg.mpApi.uniqueMpTabs();
      // 显示配置
      // 微信名字是否获取到
      if ( bg.mpApi.isNeedSetting() ) {
        var tmpTip = companyList.length > 1 ? "<br/><br/>点击右上角选择框切换您当前的大屏幕" : "";
        common.showMsg('当前的大屏幕“'+nowInfo.title+'”还未配置成功，您可以点击<a href="###" id="enterSettingPageBtn">此处</a>去配置'+tmpTip);
        $('#content').hide();
        return;
      }
      //$('.showMessageUrlBtn').trigger('click');
      setTimeout(function(){
        window.location.reload();
      }, 0);
    });

    // datetimepicker
    $('.datetimepicker').datetimepicker({
      format: 'yyyy-mm-dd hh:ii:ss',
      language: 'zh-CN',
      autoclose: true
    });

    // 设置页面
    $('.settingBtn').click(function(){

      // 初始化数据
      var config = bg.mpApi.getAutoWallConfig();
      $('#htmlCount em').text(config.htmlCount);
      $('#htmlTime em').text(config.htmlTime);
      $('#wallTime em').text(config.wallTime);

      if (config.htmlCount != 20) {
        $('#htmlCount .resetBtn').show();
      } else {
        $('#htmlCount .resetBtn').hide();
      }
      if (config.htmlTime != 8) {
        $('#htmlTime .resetBtn').show();
      } else {
        $('#htmlTime .resetBtn').hide();
      }
      if (config.wallTime != 5) {
        $('#wallTime .resetBtn').show();
      } else {
        $('#wallTime .resetBtn').hide();
      }

      $('#htmlCount small').hide();
      $('#htmlTime small').hide();
      $('#wallTime small').hide();

      var companyInfo = bg.mpApi.getCompanyInfo();
      if(!companyInfo) {
        console.log("settingBtn getCompanyInfo failed");
        return false;
      }

      // 初始化禁止关键字
      $('#completeForbidWords').val(bg.mpApi.getRuleWords('complete').join(' '));
      $('#autoWallMatchedWords').val(bg.mpApi.getRuleWords('auto_wall').join(' '));
      $('#forbidWords').val(bg.mpApi.getRuleWords('match').join(' '));

      // 是否允许同一个人重复信息上墙
      if(companyInfo.is_allow_user_repeat_message == 1) {
        $('#isAllowUserRepeatMessage')
        .children('span').text('已开启').removeClass('btn-inverse').addClass('btn-success')
        .siblings('a').text('关闭');
      } else {
        $('#isAllowUserRepeatMessage').children('span').text('已关闭').removeClass('btn-success').addClass('btn-inverse')
        .siblings('a').text('开启');
      }

      // 是否设置了自动上墙开始时间
      if(companyInfo.auto_wall_start_time) {
        var d = new Date;
        d.setTime(Date.parse(companyInfo.auto_wall_start_time));
        $('#autoWallStartTime .datetimepicker').datetimepicker('update', d);
        $('#autoWallStartTime')
        .children('.datetimepicker').show()
        .siblings('.labelStatus').hide()
        .siblings('.setBtn').text('清除');
      } else {
        $('#autoWallStartTime')
        .children('.datetimepicker').val('').hide()
        .siblings('.labelStatus').show()
        .siblings('.setBtn').text('开启');
      }

      $('.settingBox').toggle();
    });

    // 自动上墙开始时间
    $('#autoWallStartTime .setBtn').click(function(){
      var companyInfo = bg.mpApi.getCompanyInfo();
      if($(this).siblings('.labelStatus:visible').length) {
        if(companyInfo.auto_wall_start_time) {
          var d = new Date;
          d.setTime(Date.parse(companyInfo.auto_wall_start_time));
          $('#autoWallStartTime .datetimepicker').datetimepicker('update', d);
        } else {
          $('#autoWallStartTime .datetimepicker').datetimepicker('update', new Date);
          // 触发trigger
          $('#autoWallStartTime .datetimepicker').trigger('change');
        }
        $('#autoWallStartTime')
        .children('.datetimepicker').show()
        .siblings('.labelStatus').hide()
        .siblings('.setBtn').text('清除');
      } else {
        $('#autoWallStartTime')
        .children('.datetimepicker').val('').hide()
        .siblings('.labelStatus').show()
        .siblings('.setBtn').text('开启');
      }

      // 设置时间
      var time = $('#autoWallStartTime .datetimepicker').val().trim();
      if(time && !/^\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}$/.test(time)){
        common.showMsg("日期时间格式不正确");
        return false;
      }
      common.hideMsg();
      var companyInfo = bg.mpApi.getCompanyInfo();
      companyInfo.auto_wall_start_time = time;
      bg.mpApi.setCompanyInfo(companyInfo);

      $('#autoWallStartTime em').show();
    });

    // 时间改变，触发保存
    $('#autoWallStartTime .datetimepicker').on('change', function(){
      // 设置时间
      var time = $('#autoWallStartTime .datetimepicker').val().trim();
      if(time && !/^\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}$/.test(time)){
        common.showMsg("日期时间格式不正确");
        return false;
      }
      common.hideMsg();
      var companyInfo = bg.mpApi.getCompanyInfo();
      companyInfo.auto_wall_start_time = time;
      bg.mpApi.setCompanyInfo(companyInfo);
      $('#autoWallStartTime em').show();
    });

    // 切换forbidWordsBtn
    $('.forbidWordsBtn').click(function(){
      var id  = $(this).data('id');
      var dId = $(this).siblings('a').data('id');
      $('#'+dId).hide();
      $('#'+id).show();
      // 设置初始化值
      //$('#completeForbidWords').val(bg.mpApi.getRuleWords('complete').join(' '));
      //$('#forbidWords').val(bg.mpApi.getRuleWords().join(' '));
      $(this).addClass('btn-success active').siblings('a').removeClass('btn-success active');
    });

    // 重置
    $('.resetBtn').click(function(){
      var id = $(this).closest('label').attr('id').trim();
      switch(id) {
        case 'htmlCount':
          $('#htmlCount em').text(20);
          $('#htmlCount small').show();
          break;
        case 'htmlTime':
          $('#htmlTime em').text(8);
          $('#htmlTime small').show();
          break;
        case 'wallTime':
          $('#wallTime em').text(5);
          $('#wallTime small').show();
          break;
      }
      $(this).hide();
    });

    // 设置是否允许同一用户消息上墙
    $('#isAllowUserRepeatMessage a').click(function(){
      var companyInfo = bg.mpApi.getCompanyInfo();
      if(companyInfo.is_allow_user_repeat_message == 0) {
        $('#isAllowUserRepeatMessage')
        .children('span').text('已开启').removeClass('btn-inverse').addClass('btn-success')
        .siblings('a').text('关闭');
        companyInfo.is_allow_user_repeat_message = 1;
      } else {
        $('#isAllowUserRepeatMessage').children('span').text('已关闭').removeClass('btn-success').addClass('btn-inverse')
        .siblings('a').text('开启');
        companyInfo.is_allow_user_repeat_message = 0;
      }

      // 暂时保存
      bg.mpApi.setCompanyInfo(companyInfo);

      $('#isAllowUserRepeatMessage em').show();

    });

    // 配置保存
    $('.settingSaveBtn').click(function(){
      /*var config = {
        htmlCount: parseInt($('#settingHtmlCount').val()),
        htmlTime: parseInt($('#settingHtmlTime').val()),
        wallTime: parseInt($('#settingWallTime').val())
      };*/

      var companyInfo = bg.mpApi.getCompanyInfo();
      var postData = {};

      var config = {
        htmlCount: parseInt($('#htmlCount em').text()),
        htmlTime: parseInt($('#htmlTime em').text()),
        wallTime: parseInt($('#wallTime em').text())
      };

      if (!config.htmlCount || config.htmlCount > 100) {
        common.showMsg('每次获取消息数量必须是20~100之间的整数');
        return;
      }
      if (!config.htmlTime || config.htmlTime < 3) {
        common.showMsg('每次获取消息时间间隔不能小于3秒');
        return;
      }
      if (!config.wallTime || config.wallTime < 3) {
        common.showMsg('消息上墙时间间隔不能小于3秒');
        return;
      }

      // 设置自动上墙配置
      bg.mpApi.setAutoWallConfig(config);

      // 设置自定义关键词过滤
      var content = $('#forbidWords').val().trim();
      bg.mpApi.setRuleWords(content);
      postData.forbid_words = content;

      content = $('#completeForbidWords').val().trim();
      bg.mpApi.setRuleWords(content, 'complete');
      postData.complete_forbid_words = content;

      content = $('#autoWallMatchedWords').val().trim();
      bg.mpApi.setRuleWords(content, 'auto_wall');
      postData.auto_wall_matched_words = content;

      // 自动上墙起始时间
      postData.auto_wall_start_time = companyInfo.auto_wall_start_time;

      // 同一用户是否重复消息上墙
      postData.is_allow_user_repeat_message = companyInfo.is_allow_user_repeat_message;

      var url = bg.mpApi.getUrl('user/extension/save_setting_data', true);
      $.post(url, postData, function(json){
        if (json.info != 'ok') {
          common.showMsg(json.info);
        } else {
          common.showMsg('保存成功');
          $('.settingBox').hide();
          bg.mpApi.uniqueMpTabs();
          $('.wallMessageTotal .showMessageUrlBtn').trigger('click');
          setTimeout(function(){ window.close(); }, 100);
        }
      }, 'json').error(function(jqXHR, errTxt){
        common.showMsg('网络错误：（'+errTxt+'），请重试');
      });
    });

    // 自动上墙
    $('.autoWallBtn').click(function(){
      var status = bg.mpApi.getAutoWallStatus();
      var flag = status == 1 ? 0 : 1;
      bg.mpApi.setAutoWallStatus(flag);
      status = bg.mpApi.getAutoWallStatus();
      if (status == 1) {
        $('.autoWallBtn').removeClass("btn-success").addClass('btn-danger').text("关闭自动上墙").show();
      } else {
        $('.autoWallBtn').removeClass("btn-danger").addClass('btn-success').text("开启自动上墙").show();
      }
      bg.mpApi.uniqueMpTabs();
      setTimeout(function(){
        $('.wallMessageTotal .showMessageUrlBtn').trigger('click');
        setTimeout(function(){ window.close(); }, 100);
      }, 200);
    });

    // 查看大屏幕
    $('.wallMessageTotal .showScreenUrlBtn').click(function(){
      var url = bg.mpApi.getCompanyUrl('message', true);
      if( !url ) {
        common.showMsg('您还没有登录，请先登录');
        return;
      }
      chrome.tabs.query({url: url + '*', windowType: "normal"}, function(tabs){
        if ( tabs.length ) {
          for (var i =0; i<tabs.length; i++) {
            if ( tabs[i].url == url ) {
              bg.mpApi.setCurrTab(tabs[i], {
                active:true,
                highlighted:true
              });
              return;
            }
          }
        }
        window.open(url);
        setTimeout(function(){ window.close(); }, 100);
      });
    });

    // 查看实时消息
    $('.wallMessageTotal .showMessageUrlBtn').click(function(){
      bg.mpApi.getMessagePageUrl(function(url, tab){
        if (tab) {
          bg.mpApi.setCurrTab(tab, {
            active:true,
            highlighted:true,
            url: url
          });
        } else {
          window.open(url);
        }
      });
    });

    // 后台登录提示
    $('.showAdminUrlBtn').click(function(){
      var url = bg.mpApi.getUrl('user/message', true);
      if( !url ) {
        common.showMsg('您还没有登录，请先登录');
        return;
      }
      chrome.tabs.query({url: url + '*', windowType: "normal"}, function(tabs){
        if ( tabs.length ) {
          bg.mpApi.setCurrTab(tabs[0], {
            active:true,
            highlighted:true
          });
        } else {
          window.open(url);
        }
      });
    });

    // 退出
    $('.logoutBtn').click(function(){
      var url = bg.mpApi.getUrl('user/logout');
      $.post(url, function(json){
        if (json.info == 'ok') {
          window.location.reload();
        } else {
          alert(json.info);
        }
      }, 'json');
    });

    // 下墙代理，上墙
    $('.messageListBox').delegate('.dropFromWallBtn, .upFromWallBtn', 'click', null, function(e){
      var id = $(this).closest('.messageBox').attr('id').substring(8);
      if ( !id ) {
        return false;
      }
      var url = bg.mpApi.getUrl('user/extension/change_on_wall', true);
      if ( !url ) {
        common.showMsg('对不起，会话已过期。请重新点击图标登录');
        return;
      }
      var obj = $(this).closest('.messageBox');

      var isOnWall = $(this).hasClass('upFromWallBtn') ? 1 : 0;

      $.post(url, {id:id, is_on_wall: isOnWall }, function(json){
        if (json.info == 'ok') {
          if (isOnWall) {
            obj.find('.upFromWallBtn').hide().siblings('.dropFromWallBtn').show();
          } else {
            obj.find('.upFromWallBtn').show().siblings('.dropFromWallBtn').hide();
          }
          // total
          $('.showAdminUrlBtn .num').text(json.total+'条');
          bg.mpApi.setNoticeNum(json.total);
          // 通知下墙的
          if(json.flag == 0) {
            bg.mpApi.noticeOffWall(json.mp_message_id);
          }
        } else {
          common.showMsg(json.info);
        }
      }, 'json');
    });

    // ctrl+enter 搜索
    $('#searchText').keydown(function(e){
      if (e.ctrlKey && e.keyCode == 13) {
        $('.searchBox .searchBtn').trigger('click');
      }
    });

    // 消息状态切换
    $('#searchMsgType').change(function(e){
      var type = $(this).val();
      if (type == -1) {
        $('.searchOffWallBtn, .searchOnWallBtn').show();
      } else if (type == 1) {
        $('.searchOffWallBtn').show();
        $('.searchOnWallBtn').hide();
      } else if (type == 0) {
        $('.searchOffWallBtn').hide();
        $('.searchOnWallBtn').show();
      }
    });

    // 搜索
    $('#searchForm').submit(function(e){
      e.preventDefault();
      e.stopPropagation();
      var keyword = $.trim($('#searchText').val());
      var startT  = $.trim($('#searchStartTime').val());
      var endT    = $.trim($('#searchEndTime').val());
      var msgType = $('#searchMsgType').val();
      common.loading(true);
      var url = bg.mpApi.getUrl('user/extension/extension_get_message', true);
      $.getJSON(url, { 'last_id':'', 'keyword':keyword, start_time:startT, end_time:endT, message_type:msgType }, function(json){
        common.loading(false);
        if ( json.info != 'ok' ) {
          common.showMsg(json.info);
          return;
        }
        if ( !json.message_list || !json.message_list.length ) {
          if (keyword) {
            common.showMsg('暂时还没有与“'+keyword+'”相关的上墙消息');
          } else {
            common.showMsg('暂时还没有相关上墙消息');
          }
          return;
        }
        bg.mpApi.getToken(function(token){
          if (!token) {
            bg.mpApi.setSwitchPage('message');
            common.showMsg('获取token失败，请保持公众平台页面处于打开状态 '+'<a href="https://mp.weixin.qq.com" target="_blank">点此打开</a>');
            return;
          }
          common.hideMsg();
          // 渲染
          var html = '';
          $.each(json.message_list, function(k, v){
            html += renderMessage(v, token);
          });
          $('.messageListBox').html(html);
          $('.showAdminUrlBtn .num').text(json.total+'条');
        });
      });
    });

    // 批量下墙符合此条件的消息
    $('.searchOffWallBtn, .searchOnWallBtn').click(function(e){

      var thisBtn = $(this);
      if (thisBtn.attr('data-disabled') == 'yes') {
        common.showMsg('对不起，正在下墙中，请稍等');
        return false;
      }

      e.preventDefault();
      e.stopPropagation();
      var keyword = $.trim($('#searchText').val());
      var startT  = $.trim($('#searchStartTime').val());
      var endT    = $.trim($('#searchEndTime').val());
      var msgType = $('#searchMsgType').val();

      var confirmText = (!keyword && !startT && !endT) ? '您没有设置任何搜索条件，' : '';
      confirmText += '确定要执行此操作？';
      if (!confirm(confirmText)) {
        return false;
      }

      var data;
      if (thisBtn.hasClass('searchOnWallBtn')) {
        data = { 'last_id':'', 'keyword':keyword, start_time:startT, end_time:endT, 'is_on_wall':1, message_type: msgType };
      } else {
        data = { 'last_id':'', 'keyword':keyword, start_time:startT, end_time:endT, 'is_off_wall':1, message_type: msgType };
      }

      common.loading(true);
      thisBtn.attr('data-disabled', 'yes');
      var url = bg.mpApi.getUrl('user/extension/extension_get_message', true);
      $.getJSON(url, data, function(json){
        thisBtn.attr('data-disabled', 'no');
        common.loading(false);
        if ( json.info != 'ok' ) {
          common.showMsg(json.info);
          return;
        }
        common.showMsg('操作成功！');
        setTimeout(function(){
          window.location.reload();
        }, 1000);
      }).error(function(jqXHR, errText, errThrown){
        thisBtn.attr('data-disabled', 'no');
        common.showMsg('网络连接错误，请重试(' + errText + ')');
        //window.location.reload();
      });
    });

    // 滚动加载
    $(window).scroll(function(){
      var scrollTop = $(window).scrollTop();
      var height = $(document).outerHeight();
      var viewH  = $(window).height();
      if ( scrollTop/(height -viewH)>=0.95 ) {
        var id = getCurrTab();
        tabFn[id]('scrollEnd');
      }
    });

    // 发送消息按钮
    $('#sendLotteryMsgBtn').click(function(){
      //
      var msg = $('#lotteryMsgBox').val().trim();
      if(!msg) {
        $('#lotteryMsgBox').focus();
        return;
      }

      // 获取中奖用户
      var userList = null, tmp;
      if($('.lotteryUserBox').length) {
        userList = [];
        $.each($('.lotteryUserBox'), function(k, v){
          tmp = {
            id: parseInt($(this).attr('data-fakeid')),
            nick_name: $(this).find('.lotteryUserName').html(),
            group_id: 0
          };
          if(tmp.id) {
            userList.push(tmp);
          }
        });
      } else {
        common.showMsg("暂时还没有中奖用户哦~");
        return;
      }

      //组装消息

      var data = {
        groupid     : 0,
        userList    : userList,
        messageHtml : "<div style='padding:15px;'>"+msg+"</div>",
        message     : {
          content  : msg,
          imgcode  : "",
          lang     : "zh_CN",
          random   : Math.random(),
          t        : "ajax-response",
          tofakeid : 0,
          // 网页获取
          //token: "1120381898",
          // 文本类型
          type     : 1,
          f        : 'json',
          ajax     : 1

        }
      };

      // 设置群发任务
      bg.wxqf_common.messageAddTask(data, null, function(){
        bg.mpApi.getToken(function(token){

          if(!token) {
            common.showMsg("你没有打开公众平台，请先打开公众平台才能发送");
            return;
          }

          // 重置窗口
          bg.wxqf_task.resetWorkTab();
          // 关闭其他页面
          bg.mpApi.uniqueMpTabs(true);

          //跳转
          var url = bg.wxqf_common.getPageUrl('user', token);
          window.open(url+ '#wxqfzs_send');
          //window.location.href = url + '#wxqfzs_send';
        });
      });
    });
  }

  /**
   * 用户点击进入mp微信配置页面
   */
  function enterMpSettingPage()
  {
    bg.mpNotification.noti('mp_setting', '配置大屏幕', '正在进入配置页面...');
    bg.mpApi.getSettingPageTab(function(tab){
      if ( tab ) {
        bg.mpApi.setCurrTab(tab, {
          active:true,
          highlighted:true,
          url: tab.url
        });
      } else {
        // 设置即将要跳转的页面为setting
        bg.mpApi.setSwitchPage('setting');
        bg.mpApi.getSettingPageUrl(function(url, tab){
          if (tab) {
            bg.mpApi.setCurrTab(tab, {
              active:true,
              highlighted:true,
              url: url
            });
          } else {
            bg.mpApi.createTab({
              url:url,
              active:true
            });
          }
        });
      }
    });
  }

  /**
   * 渲染单条消息
   */
  function renderMessage(info, token)
  {
    //info.link = 'https://mp.weixin.qq.com/cgi-bin/singlemsgpage?token='+token+'&fromfakeid='+info.fakeid+'&msgid=&source=&count=20&t=wxm-singlechat&lang=zh_CN';
    info.link = 'https://mp.weixin.qq.com/cgi-bin/singlesendpage?tofakeid='+info.fakeid+'&t=message/send&action=index&token='+token+'&lang=zh_CN';
    if(info.is_on_wall > 0) {
      var onWallBtn = '<a href="javascript:void(0);" style="display:none;" class="pull-right btn btn-mini btn-primary wall-drop-btn upFromWallBtn">\
          <i class="icon-white icon-arrow-up"></i>上墙\
        </a>\
        <a href="javascript:void(0);" class="pull-right btn btn-mini btn-danger wall-drop-btn dropFromWallBtn">\
          <i class="icon-white icon-arrow-down"></i>下墙\
        </a>';
    } else {
      var onWallBtn = '<a href="javascript:void(0);" class="pull-right btn btn-mini btn-primary wall-drop-btn upFromWallBtn">\
          <i class="icon-white icon-arrow-up"></i>上墙\
        </a>\
        <a href="javascript:void(0);" style="display:none;" class="pull-right btn btn-mini btn-danger wall-drop-btn dropFromWallBtn">\
          <i class="icon-white icon-arrow-down"></i>下墙\
        </a>';
    }
    var html = '\
      <div class="media message-box messageBox" id="dataList'+info.id+'" data-update_time_ms="'+info.update_time_ms+'">\
        <a class="pull-left" href="'+info.link+'" target="_blank"><img width="64" class="media-object" src="'+info.avatar+'"></a>\
        <div class="media-body">\
          <h4 class="media-heading">\
            <span><a href="'+info.link+'" target="_blank">'+info.user_name+'</a></span>\
            '+onWallBtn+'\
          </h4>\
          <p>'+info.content+'</p>\
          <p class="send-time">\
            <span '+(info.mp_add_time  == '0000-00-00 00:00:00' ? 'style="display:none;"' : '')+'>发送时间: '+(info.mp_add_time == '0000-00-00 00:00:00' ? '--' : info.mp_add_time)+'</span>\
            <span '+(info.on_wall_time == '0000-00-00 00:00:00' ? 'style="display:none;"' : '')+'>上墙时间: '+(info.on_wall_time == '0000-00-00 00:00:00' ? '--' : info.on_wall_time)+'</span>\
          </p>\
        </div>\
      </div>';
    return html;
  }

  /**
   * 渲染单条加星消息
   * @return {[type]} [description]
   */
  function renderTagMessage(info, token)
  {
    info.link = 'https://mp.weixin.qq.com/cgi-bin/singlesendpage?tofakeid='+info.fakeid+'&t=message/send&action=index&token='+token+'&lang=zh_CN';
    var onWallBtn = '\
      <a href="javascript:void(0);" class="pull-right btn btn-mini btn-danger wall-drop-btn untagBtn">\
        <i class="icon-white icon-arrow-down"></i>取消加星\
      </a>';
    var html = '\
      <div class="media message-box tagMessageBox" data-id="'+info.id+'" data-tag_relation_id="'+info.tag_relation_id+'">\
        <a class="pull-left" href="'+info.link+'" target="_blank"><img width="64" class="media-object" src="'+info.avatar+'"></a>\
        <div class="media-body">\
          <h4 class="media-heading">\
            <span><a href="'+info.link+'" target="_blank">'+info.user_name+'</a></span>\
            '+onWallBtn+'\
          </h4>\
          <p>'+info.content+'</p>\
          <p class="send-time">\
            <span '+(info.mp_add_time  == '0000-00-00 00:00:00' ? 'style="display:none;"' : '')+'>发送时间: '+(info.mp_add_time == '0000-00-00 00:00:00' ? '--' : info.mp_add_time)+'</span>\
            <span '+(info.on_wall_time == '0000-00-00 00:00:00' ? 'style="display:none;"' : '')+'>上墙时间: '+(info.on_wall_time == '0000-00-00 00:00:00' ? '--' : info.on_wall_time)+'</span>\
          </p>\
        </div>\
      </div>';
    return html;
  }

  /**
   * 渲染中奖用户 单个
   */
  function renderLotteryUser(info, token)
  {
    info.link = 'https://mp.weixin.qq.com/cgi-bin/singlesendpage?tofakeid='+info.fakeid+'&t=message/send&action=index&token='+token+'&lang=zh_CN';
    var html = '\
      <div class="media message-box lotteryUserBox" data-id="'+info.id+'" data-fakeid="'+info.fakeid+'">\
        <a class="pull-left" href="'+info.link+'" target="_blank"><img width="64" class="media-object" src="'+info.avatar+'"></a>\
        <div class="media-body">\
          <h4 class="media-heading">\
            <span><a href="'+info.link+'" target="_blank" class="lotteryUserName">'+(info.user_name || info.name)+'</a></span>\
            <span class="pull-right label label-info">'+info.view_order+'</span>\
          </h4>\
        </div>\
      </div>';
    return html;

  }

  function loginPoll()
  {
    // 检查登录
    var url = bg.mpApi.getUrl('user/check_login');
    setInterval(function(){
      $.getJSON(url, function(data){
        if ( data.is_login) {
          window.location.reload();
        }
      });
    }, 3000);
  }

  /**
   * 获取当前的tab
   */
  function getCurrTab()
  {
    var id = parseInt($('#navbar li.active').data('id'));
    return id;
  }
  
  /**
   * 是否摇显示版本提示
   */
  function showVersionTip()
  {
    // 检查版本
    $.get(chrome.extension.getURL('manifest.json'), function(info){
        version = info.version;
        tmpArr = version.split('.');
      
        $.get(bg.mpApi.getUrl('user/extension/get_version', true), function(data){
          var greater_or_equal_version = data.greater_or_equal_version;
          var getTmpArr = greater_or_equal_version.split('.');
          
        if (tmpArr[2] < getTmpArr[2]) {
          $('.banner-box').hide();
          $('.container').hide();
          $('.versionTip').html(data.tip_content).show();
        }
        }, 'json');
      
      }, 'json');
    
  }
});